//
//  Ext+DateGroup.swift
//  Crazy
//
//  Created by ming on 2024/11/12.
//

import Foundation

struct DateGroupHandler {
    /// 将日期数组按照指定小时间隔分组
    /// - Parameters:
    ///   - dates: 日期数组
    ///   - hourInterval: 小时间隔（默认2小时）
    /// - Returns: 按时间间隔分组后的字典，键为时间段字符串，值为该时间段内的日期数组
    static func groupDates(_ dates: [Date], byHourInterval hourInterval: Int = 2) -> [String: [Date]] {
        // 确保日期数组已排序
        let sortedDates = dates.sorted()
        
        // 用于存储分组结果
        var groups: [String: [Date]] = [:]
        
        // 日历对象
        let calendar = Calendar.current
        
        for date in sortedDates {
            // 获取当天的开始时间
            let startOfDay = calendar.startOfDay(for: date)
            
            // 获取当前小时
            let hour = calendar.component(.hour, from: date)
            
            // 计算所属的时间段
            let groupIndex = hour / hourInterval
            let groupStartHour = groupIndex * hourInterval
            let groupEndHour = groupStartHour + hourInterval
            
            // 创建时间段标识
            let timeRangeKey = String(format: "%02d:00-%02d:00", groupStartHour, groupEndHour)
            
            // 将日期添加到对应的组
            if groups[timeRangeKey] == nil {
                groups[timeRangeKey] = [date]
            } else {
                groups[timeRangeKey]?.append(date)
            }
        }
        
        return groups
    }
    
    /// 更灵活的分组方法，支持自定义时间范围格式
    static func groupDates( _ dates: [Date], byHourInterval hourInterval: Int = 2, formatStyle: DateIntervalFormatter.Style = .short) -> [String: [Date]] {
        let sortedDates = dates.sorted()
        var groups: [String: [Date]] = [:]
        let calendar = Calendar.current
        
        // 配置时间区间格式化器
        let intervalFormatter = DateIntervalFormatter()
        intervalFormatter.timeStyle = formatStyle
        intervalFormatter.dateStyle = .none
        
        for date in sortedDates {
            let hour = calendar.component(.hour, from: date)
            let groupIndex = hour / hourInterval
            
            // 计算时间区间
            var components = DateComponents()
            components.hour = groupIndex * hourInterval
            guard let groupStartDate = calendar.date(bySettingHour: groupIndex * hourInterval, minute: 0, second: 0, of: date) else { continue }
            guard let groupEndDate = calendar.date(byAdding: .hour, value: hourInterval, to: groupStartDate) else { continue }
            
            // 格式化时间区间
            let timeRangeKey = intervalFormatter.string(from: groupStartDate, to: groupEndDate)
            
            if groups[timeRangeKey] == nil {
                groups[timeRangeKey] = [date]
            } else {
                groups[timeRangeKey]?.append(date)
            }
        }
        
        return groups
    }
    
    /// 使用示例
    static func example() {
        // 创建示例数据
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let dates: [Date] = [
            dateFormatter.date(from: "2024-11-01 01:30:00")!,
            dateFormatter.date(from: "2024-11-01 02:15:00")!,
            dateFormatter.date(from: "2024-11-01 03:45:00")!,
            dateFormatter.date(from: "2024-11-01 05:20:00")!,
            dateFormatter.date(from: "2024-11-01 07:10:00")!,
            dateFormatter.date(from: "2024-11-01 09:00:00")!
        ]
        
        // 按2小时分组
        let groupedDates = groupDates(dates)
        
        // 打印分组结果
        for (timeRange, datesInGroup) in groupedDates.sorted(by: { $0.key < $1.key }) {
            print("\n时间段: \(timeRange)")
            for date in datesInGroup {
                print(dateFormatter.string(from: date))
            }
        }
    }
}

// MARK: - 实用的扩展方法
extension Date {
    func isSameTimeInterval(as date: Date, hourInterval: Int) -> Bool {
        let calendar = Calendar.current
        let hour1 = calendar.component(.hour, from: self)
        let hour2 = calendar.component(.hour, from: date)
        return hour1 / hourInterval == hour2 / hourInterval
    }
}
